local oo = require("SharedLibs.BaseLib")
local co = require("SharedLibs.CoroLib")

Debugger = require("SharedLibs.Debugger")

ISignal = require("SharedLibs.Signal.ISignal")
IEmitter = require("SharedLibs.Signal.IEmitter")
IReadOnlyProperty = require("SharedLibs.Signal.IReadOnlyProperty")

Signal = require("SharedLibs.Signal.Signal")

--- SignalWrapper只能传递数据，没有Emit方法直接发射数据
local cls = oo.class();
cls:implements(ISignal);
--cls:implements(IEmitter);
cls:implements(IReadOnlyProperty);

--- 注册到co里
co.SignalWrapper = cls;

--- dataWrapper接收任意个参数(...)， 返回 (ret, ...)。
--- 返回值：第一个是false，则这个data被过滤掉。否则，将Emit(...)
function cls:constructor(srcSignal, initVal, name)
	assert(srcSignal);
	
	self._changed = Signal.new();
	self._srcSignal = srcSignal;
	
	self._value = initVal;
	
	self.name = name or "Signal2PropMapper";
end

--function cls:Emit(...)
--	self._changed:Emit(...);
--end

function cls:GetValue()
	return self._value;
end

cls.Get = cls.GetValue;

function cls:_setValue(value)
	if value == self._value then return end;
	self._value = value;
	self._changed:Emit(value);
end


function cls:On(handler, retDestroyer)	 
	self._changed:On(handler);
	 
	if self._changed:GetHandlerCount() == 1 then
		self._onSrcSignal = function(val)
			self:_setValue(val);
		end;
		self._srcSignal:On(self._onSrcSignal);
	end
	if retDestroyer then return function() self:Off(handler); end end	
end

function cls:Off(handler) 
	self._changed:Off(handler);

	if self._changed:GetHandlerCount() == 0 then
		self._srcSignal:Off(self._onSrcSignal);
		self._onSrcSignal = nil;
	end
end

function cls:Clear()
	if self._changed:GetHandlerCount() == 0 then return end;
 
	self._changed:Clear();

	self._srcSignal:Off(self._onSrcSignal);
	self._onSrcSignal = nil;
end

function cls:GetHandlerCount()
	return self._changed:GetHandlerCount();
end

function cls:HasHandler(listener)
	return self._changed:HasHandler(listener);
end

return cls;
